package com.zjpg.forum.services.impl;

import com.zjpg.forum.common.AppResult;
import com.zjpg.forum.common.ResultCode;
import com.zjpg.forum.dao.UserMapper;
import com.zjpg.forum.exception.ApplicationException;
import com.zjpg.forum.model.User;
import com.zjpg.forum.services.IUserSevice;
import com.zjpg.forum.util.MD5Util;
import com.zjpg.forum.util.StringUtil;
import com.zjpg.forum.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName UserSeviceImpl
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/8/10 17:08
 */
@Slf4j
@Service
public class UserSeviceImpl implements IUserSevice {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        // 1、非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername(), user.getNickname(), user.getPassword(), user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2、按用户查询用户名信息
        User existuser = userMapper.selectByUserName(user.getUsername());
        // 2.1 判断用户名是否存在
        if (existuser != null) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        // 新增用户流程，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 设置当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 打印日志
        log.info("新增用户成功，username = " + user.getUsername() + " . ");
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 1.非空校验
        if (StringUtil.isEmpty(username, password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.获取用户信息
        User user = userMapper.selectByUserName(username);
        // 3.判断user是否为空
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 4.根据用户输入的密码生成密文
        String ciphertext = MD5Util.md5Salt(password, user.getSalt());
        // 5.判断密码是否一致
        if (!ciphertext.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 6.打印日志
        log.info("登录成功 username = " + username);
        return user;
    }


    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL + "user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "受影响的行数不为：1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL + "user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "受影响的行数不为：1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改个人信息
     *
     * @param user
     */
    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if (existUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        boolean checkAttr = false;
        User updateUser = new User();
        updateUser.setId(user.getId());

        //if (StringUtil.isEmpty(user.getUsername())) {
        //
        //}

        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

        if (user.getGender() != null
                && user.getGender() != existUser.getGender()) {
            updateUser.setGender(user.getGender());
            if (user.getGender() > 2 || user.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }

        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        if (!checkAttr) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 修改密码
     * @param id
     * @param oldPassward
     * @param newPassward
     */
    @Override
    public void modifyPassward(Long id, String oldPassward, String newPassward) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String oldEncryptPassward = MD5Util.md5Salt(oldPassward,user.getSalt());
        if (!oldEncryptPassward.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_PWD_NOT_TRUE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PWD_NOT_TRUE));
        }
        String salt = UUIDUtil.UUID_32();
        String newEncryptPassward = MD5Util.md5Salt(newPassward,salt);

        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(newEncryptPassward);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }


    // 修改AvatarUrl
    @Override
    public void modifyAvatar(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }
}
